// Package datasource @author dingrui @since 2021/11/26
package datasource

import (
	"fmt"
	"log"
	"time"

	"github.com/gomodule/redigo/redis"
)

var (
	// 单例
	G_redis *RedisCli
)

//
//  RedisCli
//  @Description: redis客户端
//                连接池
//
type RedisCli struct {
	pool      *redis.Pool
	showDebug bool
}

func init() {
	// 单例赋值
	G_redis = newRedisConnection()
}

func (rds *RedisCli) Do(command string, args ...interface{}) (reply interface{}, err error) {
	conn := rds.pool.Get()
	defer conn.Close()

	t1 := time.Now().UnixNano()
	reply, err = conn.Do(command, args...)
	if err != nil {
		e := conn.Err()
		if e != nil {
			log.Println("rdshelper Do", err, e)
		}
	}
	t2 := time.Now().UnixNano()
	if rds.showDebug {
		fmt.Printf("[redis] [info] [%dus]cmd=%s, err=%s, args=%v, reply=%s\n", (t2-t1)/1000, command, err, args, reply)
	}
	return reply, err
}

func (rds *RedisCli) ShowDebug(b bool) {
	rds.showDebug = b
}

//
//  newRedisConnection
//  @Description: 创建redis连接
//  @return *RedisCli
//
func newRedisConnection() (client *RedisCli) {
	pool := redis.Pool{
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", fmt.Sprintf("%s:%d", "localhost", 6379), redis.DialPassword("19920308"))
			if err != nil {
				log.Fatal("rdshelper.NewCache Dial error ", err)
				return nil, err
			}
			return c, nil
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			if time.Since(t) < time.Minute {
				return nil
			}
			_, err := c.Do("PING")
			return err
		},
		MaxIdle:         10000,
		MaxActive:       10000,
		IdleTimeout:     0,
		Wait:            false,
		MaxConnLifetime: 0,
	}
	client = &RedisCli{
		pool:      &pool,
		showDebug: true,
	}
	return
}
